/* 
 * File:   XUDPShareMem.h
 * Author: minaev
 *
 * Created on 5 Ноябрь 2013 г., 15:50
 */

#ifndef XUDPSHAREMEM_H
#define	XUDPSHAREMEM_H

#include <stdint.h>
#include <pthread.h>

#include "XUDPServ.h"
#include "XshareMem.h"

#define MAGIC_NUM 0xbee4

#define UC_READ                 2
#define UC_WRITE                4
#define UC_BROADCAST            6
#define UC_ADD                  8
#define UC_REMOVE               10
#define UC_LENLINE              12
#define UC_ADD_DEV              14
#define UC_REM_DEV              16
#define UC_LENMEM               18

//    0     1     2     3     4     5     6     7     8     9    10    11     l-2   l-1
// +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+- - - +-----+-----+
// |  0xbee4   |   length  | cmd |   nLine   |   nBlock  |  cntBlock | data |    CRC    |
// +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+- - - +-----+-----+
//                         |                   PACK                         |

#define OFST_MAGIC   0
#define OFST_LENGTH  2
#define OFST_CMD     4
#define OFST_NLINE   5
#define OFST_NBLOCK  7
#define OFST_CBLOCK  9
#define OFST_DATA    11

#define SUM_WITHOUT_DATA 13
#define SUM_WITHOUT_PACK 6

#define DST_UDP_PORT 21215

class XUDPShareMem {
public:
    XUDPShareMem(XUDPServ* serv, XshareMem* shrmem);
    virtual ~XUDPShareMem();
    int processBuf(const char* buf, int16_t len,uint32_t ip);
    static uint16_t getCRC(char* buf,uint32_t len);
    int sendPack(uint32_t ip,uint8_t cmd,uint16_t nLine,uint16_t nBlock, uint16_t cntBlocks);
private:
    char* packReadReq(const char* buf, uint16_t len);
    char* packWriteReq(const char* buf, uint16_t len);
    char* formPack(uint8_t cmd,uint16_t nLine,uint16_t nBlock, uint16_t cntBlocks);
    int unpackWriteMem(const char* buf, int16_t len);
    void setMagLenBuf(char* buf,uint32_t len);
    void setShareFieldsBuf(char* buf, uint32_t len,uint8_t cmd,
        uint16_t nLine,uint16_t nBlock,uint16_t ncntBlock);
    void setFieldsBuf(char* buf, uint32_t len,uint8_t cmd,
        uint16_t nLine,uint16_t nBlock,uint16_t ncntBlock, const void* data);
    XUDPServ* serv;
    XshareMem* shrmem;
    pthread_mutex_t assccFormPack;
};

#endif	/* XUDPSHAREMEM_H */

